"""
统计10MIN内的掉包率。
1、用 Ping 命令
2、多线程 10min后 杀掉进程
"""
import os, time


def open_file_ping():
    with open("./Support/ping.txt", mode="r", encoding="gbk") as ping:
        info = ping.read().split("\n")
    return info[-5:]


def nowTime():
    a = time.strftime("%Y-%m-%d %H:%M:%S")
    return "[" + a + "] "


def main():
    Time = 100
    IP = "qq.com"
    print(f"开始Ping {IP} {Time}次")
    breakTime = 10
    while breakTime:
        try:
            os.system(f"echo {nowTime()} >> ./Support/ping.txt")
            os.system(f"ping -n {Time} -w 1000 {IP} >> ./Support/ping.txt")
            Ping = open_file_ping()
            print(Ping)
            Ping[0] = IP + Ping[0][-13:]
            ping_str = "\n" + nowTime() + Ping[0] + Ping[1][8:] + Ping[3][4:]
            print(ping_str)
            with open("./Support/Ping_log.txt", encoding="gbk", mode="a") as log:
                log.write(ping_str)
            input("按回车键终止")
            exit(0)  # exit
        except IndexError:
            print("ping 失败，\n"
                  "*****************\n"
                  "脚本退出...")
            input("按回车键终止")
            exit(-1)
        except FileNotFoundError:
            print("文件没找到")
            input("按回车键继续")
            os.system(f"{nowTime()} > ./Support/ping.txt")
            os.system(f"ping -n {Time} -w 1000 {IP} >> ping.txt")
            breakTime -= 1


if __name__ == "__main__":
    main()
